﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FlickrNet;
using System.IO;
using System.Configuration;
using log4net;
using Social;


namespace Social.FlickrApi
{
	public class FlickrApi : Social.ISocialNetwork
	{
		private readonly Flickr flickr;

		private readonly IFlickrConfig config;

		public FlickrApi(IFlickrConfig config)
		{
			Flickr.CacheDisabled = true;
			this.config = config;
			if (!string.IsNullOrEmpty(config.UserToken))
				flickr = new Flickr(config.AppKey, config.AppSecret, config.UserToken);
			else
				flickr = new Flickr(config.AppKey, config.AppSecret);
		}

		public bool IsAuthenticated
		{
			get { return flickr.IsAuthenticated; }
		}

		public string ConnectUrl
		{
			get { return flickr.AuthCalcWebUrl(AuthLevel.Delete); }
		}

		public void Login()
		{
			HttpContext.Current.Response.Redirect(flickr.AuthCalcWebUrl(AuthLevel.Delete));
		}

		public PhotoInfo UploadPhoto(FileInfo file, string title, string description, string tags, bool isPublic, bool isFamily, bool isFriend, HiddenFromSearch searchVisibilty)
		{
			string photoId;
			using (var fileStream = file.OpenRead())
			{
				photoId = flickr.UploadPicture(fileStream, title, description, tags, Convert.ToInt32(isPublic),
												   Convert.ToInt32(isFamily), Convert.ToInt32(isFriend), ContentType.Photo,
												   SafetyLevel.None, searchVisibilty);
				if (string.IsNullOrEmpty(photoId))
					return null;
			}
			return flickr.PhotosGetInfo(photoId);
		}

		public void Authenticate()
		{
			var frob = HttpContext.Current.Request.Params["frob"];
			if (string.IsNullOrEmpty(frob))
				HttpContext.Current.Response.Redirect("/");
			var auth = flickr.AuthGetToken(frob);
			if (auth != null && !string.IsNullOrEmpty(auth.Token))
				// TODO: encode value
				//HttpContext.Current.Response.Cookies.Add(new HttpCookie("flickr_token", auth.Token) {Expires = DateTime.Now.AddDays(1)});
				config.UserToken = auth.Token;
			else
				HttpContext.Current.Response.Redirect("/");
		}
	}
}
